﻿Imports System.ComponentModel
Imports System.Security.Cryptography
Imports System.Collections.ObjectModel

Namespace Tools

Public Class Hash

    ''' <summary>
    ''' Generates MD5 from a file
    ''' </summary>
    ''' <param name="pathName">Path of the file</param>
    ''' <param name="mySqlFormat">If True, the generated MD5 will be mySql-compliant, otherwise it will be .net like</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetMD5_fromFile(ByVal pathName As String, Optional ByVal mySqlFormat As Boolean = False) As String

        If mySqlFormat Then Throw New NotImplementedException

        Dim fs As System.IO.FileStream = System.IO.File.OpenRead(pathName)
        Dim sscMD5 = System.Security.Cryptography.MD5.Create
        Dim mHash = sscMD5.ComputeHash(fs)
        Dim ret As String = Convert.ToBase64String(mHash)

        Return ret

    End Function

    ''' <summary>
    ''' Returns the MD5 has of a string (using UTF8 engoding)
    ''' </summary>
    ''' <param name="Text">Text to be hashed</param>
    ''' <param name="mySqlFormat">If True, the generated MD5 will be mySql-compliant, otherwise it will be .net like</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetMD5_fromString(ByVal Text As String, Optional ByVal mySqlFormat As Boolean = False) As String

        If Not mySqlFormat Then Throw New NotImplementedException

        Dim MD5 As New MD5CryptoServiceProvider
        Dim byteValue() As Byte = System.Text.Encoding.UTF8.GetBytes(Text)
        Dim hashValue() As Byte = MD5.ComputeHash(byteValue)

        Dim ret = BitConverter.ToString(hashValue)

        Dim i As Integer = ret.Length
        Do While i > 3
            ret = ret.Remove(i - 3, 1)
            i -= 3
        Loop

        Return ret.ToLower

    End Function

End Class

End Namespace